package com.qiantu.phone.ui.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.BaseAdapter;
import com.hjq.widget.layout.SettingBar;
import com.lxj.xpopup.XPopup;
import com.qiantu.api.entity.LinkageBean;
import com.qiantu.api.entity.LinkageNewBean;
import com.qiantu.api.entity.WeatherValueBean;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.bean.LocationData;
import com.qiantu.phone.bean.WeatherTypeBean;
import com.qiantu.phone.ui.activity.map.LocationActivity;
import com.qiantu.phone.ui.adapter.ListLabelAdapter;
import com.qiantu.phone.ui.adapter.WeatherTypeAdapter;
import com.qiantu.phone.ui.adapter.WeatherValueAdapter;
import com.qiantu.phone.ui.dialog.BottomCheckListDialog;
import com.qiantu.phone.ui.dialog.BottomListDialog;
import com.qiantu.phone.utils.LinkageDataHolder;
import com.qiantu.phone.utils.WeatherConditionTypeParseUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class WeatherActivityNew  extends AppActivity {
    private SettingBar settingAction;
    private SettingBar settingReferenceArea;
    private TextView tvWeatherCondition;
    private RecyclerView recyclerView;
    private WeatherTypeAdapter mWeatherTypeAdapter;
    private BottomCheckListDialog mBottomCheckListDialog;
    private int mClickWeatherType;
    private SparseArray<List<WeatherValueBean>> selectedWeather = new SparseArray();
    private int weatherTypeXor = -1;
    private LinkageNewBean mLinkageBean;
    private LinkageNewBean.LinkageWeatherCondition mLinkageCondition;
    private List<WeatherTypeBean> weatherTypeList;
    private BottomListDialog mBottomActionDialog;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_weather_new;
    }

    @Override
    protected void initView() {
        settingAction = findViewById(R.id.setting_action);
        settingReferenceArea = findViewById(R.id.setting_reference_area);
        tvWeatherCondition = findViewById(R.id.tv_weather_condition);
        recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mWeatherTypeAdapter = new WeatherTypeAdapter(getContext());
        weatherTypeList = WeatherConditionTypeParseUtil.parseData(getContext());
        mWeatherTypeAdapter.setData(weatherTypeList);
        recyclerView.setAdapter(mWeatherTypeAdapter);
        mWeatherTypeAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                WeatherTypeBean weatherType = mWeatherTypeAdapter.getData().get(position);
                mClickWeatherType = weatherType.getType();
                if(weatherType.getValues().size() == 1){
                    WeatherValueBean weatherValueBean = weatherType.getValues().get(0);
                    List<WeatherValueBean> selectedWeatherValues = new ArrayList<>();
                    selectedWeatherValues.add(weatherValueBean);
                    int res = getResources().getIdentifier(weatherValueBean.getName(), "string", getContext().getPackageName());
                    String weatherName = getString(res);
                    tvWeatherCondition.setText(getString(R.string.effective_when_time_holder, weatherName));
                    selectedWeather.clear();
                    selectedWeather.put(mClickWeatherType, selectedWeatherValues);
                    mWeatherTypeAdapter.checkSelected(mClickWeatherType);
//                    mWeatherTypeAdapter.setSelectedValues(selectedWeatherValues);
                }else{
                    showBottomCheckListDialog(weatherType.getValues());
                }
            }
        });
        setOnClickListener(settingReferenceArea,settingAction);
    }

    @Override
    protected void initData() {
        mLinkageBean = LinkageDataHolder.getLinkageDataNew();
        if(!getBoolean("isAdd")){
            int position = getInt("position");
            mLinkageCondition = (LinkageNewBean.LinkageWeatherCondition) mLinkageBean.getConditions().get(position);
        }
        List<LinkageNewBean.LinkageBaseCondition> linkageConditions = mLinkageBean.getConditions();
        if(mLinkageCondition == null){
            mLinkageCondition = new LinkageNewBean.LinkageWeatherCondition();
            mLinkageCondition.setConditionTypeId(4);
            mLinkageCondition.setActionTypeId(1);
            mLinkageCondition.setAreaTypeId(2);
            mLinkageCondition.setLongitude(AppApplication.getInstance().getCurHouseInfo().getLongitude());
            mLinkageCondition.setLatitude(AppApplication.getInstance().getCurHouseInfo().getLatitude());
            mLinkageCondition.setAreaName(AppApplication.getInstance().getCurHouseInfo().getProvince() + " " + AppApplication.getInstance().getCurHouseInfo().getCity() + " " + AppApplication.getInstance().getCurHouseInfo().getDistrict());
            mLinkageCondition.setAreaCode(AppApplication.getInstance().getCurHouseInfo().getDistrictId());
            mLinkageCondition.setSort(linkageConditions.indexOf(mLinkageCondition) + 1);
        }
        updateView();
    }

    private void updateView(){
        settingReferenceArea.setRightText(mLinkageCondition.getAreaName());
        if(mLinkageCondition.getWeatherKeyValue() != null){
//            try {
//                JSONArray jsonArray = new JSONArray(weatherKeyValue);
//                List<WeatherValueBean> selectedWeatherValues = new ArrayList<>();
//                List<WeatherValueBean> weatherValues = new ArrayList<>();
//                StringBuilder stringBuilder = new StringBuilder();
//                for(int i=0; i<jsonArray.length(); i++){
////                    String name = jsonArray.getJSONObject(i).getString("Name");
//                    int value = jsonArray.getJSONObject(i).getInt("Value");
//                    if(weatherValues.size() == 0){
//                        out:
//                        for(WeatherTypeBean weatherTypeBean : weatherTypeList){
//                            for(WeatherValueBean weatherValueBean : weatherTypeBean.getValues()){
//                                if(weatherValueBean.getValue() == value){
//                                    weatherValues = weatherTypeBean.getValues();
//                                    selectedWeatherValues.add(new WeatherValueBean(value, weatherValueBean.getName()));
//                                    int res = getResources().getIdentifier(weatherValueBean.getName(), "string", getContext().getPackageName());
//                                    stringBuilder.append(getString(res)).append("、");
//                                    break out;
//                                }
//                            }
//                        }
//                    }else{
//                        for(WeatherValueBean weatherValueBean : weatherValues){
//                            if(weatherValueBean.getValue() == value){
//                                selectedWeatherValues.add(new WeatherValueBean(value, weatherValueBean.getName()));
//                                int res = getResources().getIdentifier(weatherValueBean.getName(), "string", getContext().getPackageName());
//                                stringBuilder.append(getString(res)).append("、");
//                                break;
//                            }
//                        }
//                    }
//                }
//                tvWeatherCondition.setText(getString(R.string.effective_when_time_holder, stringBuilder.substring(0, stringBuilder.length() - 1)));
//                selectedWeather.put(weatherTypeXor, selectedWeatherValues);
//                mWeatherTypeAdapter.checkSelected(weatherTypeXor);
//                if(weatherValues.size() > 1){
//                    mWeatherTypeAdapter.setSelectedValues(selectedWeatherValues);
//                }
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }
            List<WeatherValueBean> selectedWeatherValues = new ArrayList<>();
            List<WeatherValueBean> weatherValues = new ArrayList<>();
            StringBuilder stringBuilder = new StringBuilder();
            for(WeatherValueBean weatherValue : mLinkageCondition.getWeatherKeyValue()){
                int value = weatherValue.getValue();
                if(weatherValues.size() == 0){
                    out:
                    for(WeatherTypeBean weatherTypeBean : weatherTypeList){
                        for(WeatherValueBean weatherValueBean : weatherTypeBean.getValues()){
                            if(weatherValueBean.getValue() == value){
                                weatherTypeXor = weatherTypeBean.getType();
                                weatherValues = weatherTypeBean.getValues();
                                selectedWeatherValues.add(new WeatherValueBean(value, weatherValueBean.getName()));
                                int res = getResources().getIdentifier(weatherValueBean.getName(), "string", getContext().getPackageName());
                                stringBuilder.append(getString(res)).append("、");
                                break out;
                            }
                        }
                    }
                }else{
                    for(WeatherValueBean weatherValueBean : weatherValues){
                        if(weatherValueBean.getValue() == value){
                            selectedWeatherValues.add(new WeatherValueBean(value, weatherValueBean.getName()));
                            int res = getResources().getIdentifier(weatherValueBean.getName(), "string", getContext().getPackageName());
                            stringBuilder.append(getString(res)).append("、");
                            break;
                        }
                    }
                }
            }
            tvWeatherCondition.setText(getString(R.string.effective_when_time_holder, stringBuilder.substring(0, stringBuilder.length() - 1)));
            selectedWeather.put(weatherTypeXor, selectedWeatherValues);
            mWeatherTypeAdapter.checkSelected(weatherTypeXor);
            if(weatherValues.size() > 1){
                mWeatherTypeAdapter.setSelectedValues(selectedWeatherValues);
            }
        }

        settingAction.setRightText(mLinkageCondition.getActionTypeId() == 1 ? R.string.linkage_action_become : R.string.linkage_action_keep);
    }

    @Override
    public void onRightClick(View view) {
        if(TextUtils.isEmpty(mLinkageCondition.getAreaName())){
            toast(R.string.please_select_reference_area_hint);
            return;
        }
        if(selectedWeather.size() == 0){
            toast(R.string.please_select_specific_weather);
            return;
        }
        if(getBoolean("isAdd")){
            mLinkageBean.getConditions().add(mLinkageCondition);
        }else{
            int position = getInt("position");
            mLinkageBean.getConditions().remove(position);
            mLinkageBean.getConditions().add(position,mLinkageCondition);
        }
        weatherTypeXor = selectedWeather.keyAt(0);
        mLinkageCondition.setWeatherKeyValue(selectedWeather.get(weatherTypeXor));
        if(weatherTypeList != null){
            for(WeatherTypeBean weatherType : weatherTypeList){
                if(weatherType.getType() == weatherTypeXor){
                    mLinkageCondition.setIcon(weatherType.getImage());
                    break;
                }
            }
        }
        startActivity_SingleTask(EditLinkageActivityNew.class);
        finish();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.setting_action:
                showBottomListDialog();
                break;
            case R.id.setting_reference_area:
                Intent intent = new Intent(getContext(), LocationActivity.class);
                LocationData locationData = new LocationData();
                if (mLinkageCondition.getLongitude() > 0 && mLinkageCondition.getLatitude() > 0) {
                    locationData.location = mLinkageCondition.getLongitude() + ":" + mLinkageCondition.getLatitude();
                } else {
                    if (AppApplication.getInstance().getCurHouseInfo() != null) {
                        locationData.location = AppApplication.getInstance().getCurHouseInfo().getLongitude() + ":" + AppApplication.getInstance().getCurHouseInfo().getLatitude();
                    }
                }
                LocationActivity.startForResult(this, locationData, 1, LocationActivity.LOCATION_REQUEST_CODE);
                break;
        }
//        showBottomDistrictDialog();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            if (requestCode == LocationActivity.LOCATION_REQUEST_CODE) {
                LocationData locationData = (LocationData) data.getSerializableExtra("DATA");
                mLinkageCondition.setLongitude(locationData.longitude);
                mLinkageCondition.setLatitude(locationData.latitude);
                mLinkageCondition.setAreaName(locationData.province + " " + locationData.city + " " + locationData.district);
//                areaCoding = locationData.provinceId + locationData.cityId + locationData.districtId;
                settingReferenceArea.setRightText(mLinkageCondition.getAreaName());
            }
        }
    }

    //    private BottomDistrictDialog mBottomDistrictDialog;
//    private void showBottomDistrictDialog(){
//        if (mBottomDistrictDialog == null) {
//            mBottomDistrictDialog = new BottomDistrictDialog(this);
//            mBottomDistrictDialog.setDialogClickListener(new BottomDistrictDialog.DialogClickListener() {
//                @Override
//                public void onConfirmClick(String text, String code) {
//                    areaName = text;
//                    areaCoding = code;
//                    settingReferenceArea.setRightText(areaName);
//                    mBottomDistrictDialog.dismiss();
//                }
//            });
//            new XPopup.Builder(this)
//                    .dismissOnBackPressed(true)
//                    .enableDrag(true)
//                    .asCustom(mBottomDistrictDialog);
//        }
//        mBottomDistrictDialog.show();
//    }

    private void showBottomCheckListDialog(List<WeatherValueBean> weatherValues) {
        if (mBottomCheckListDialog == null) {
            mBottomCheckListDialog = new BottomCheckListDialog(this);
            mBottomCheckListDialog.setDialogClickListener(new BottomCheckListDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {
                    WeatherValueAdapter adapter = (WeatherValueAdapter) mBottomCheckListDialog.getAdapter();
                    Map<Integer, WeatherValueBean> selected =  adapter.getSelected();
                    if(selected != null && selected.size() > 0){
                        selectedWeather.clear();
                        List<WeatherValueBean> selectedWeatherValues = new ArrayList<>();
                        StringBuilder stringBuilder = new StringBuilder();
                        for(int key : selected.keySet()){
                            selectedWeatherValues.add(selected.get(key));
                            int res = getResources().getIdentifier(selected.get(key).getName(), "string", getContext().getPackageName());
                            stringBuilder.append(getString(res)).append("、");
                        }
                        tvWeatherCondition.setText(getString(R.string.effective_when_time_holder, stringBuilder.substring(0, stringBuilder.length() - 1)));
                        mBottomCheckListDialog.dismiss();
                        selectedWeather.put(mClickWeatherType, selectedWeatherValues);
                        mWeatherTypeAdapter.checkSelected(mClickWeatherType);
                        if(adapter.getData().size() > 1){
                            mWeatherTypeAdapter.setSelectedValues(selectedWeatherValues);
                        }
                    }else{
                        toast(R.string.please_select_specific_weather);
                    }
                }
            });
            WeatherValueAdapter weatherValueAdapter = new WeatherValueAdapter(this);
            mBottomCheckListDialog.setAdapter(weatherValueAdapter);
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomCheckListDialog);
        }
        WeatherValueAdapter weatherValueAdapter = (WeatherValueAdapter) mBottomCheckListDialog.getAdapter();
        weatherValueAdapter.setData(weatherValues);
        weatherValueAdapter.checked(selectedWeather.get(mClickWeatherType));
        mBottomCheckListDialog.show();
    }

    private void showBottomListDialog() {
        if (mBottomActionDialog == null) {
            mBottomActionDialog = new BottomListDialog(this);
            mBottomActionDialog.setDialogClickListener(new BottomListDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {

                }
            });
            ListLabelAdapter listLabelAdapter = new ListLabelAdapter(this);
            List<String> data = new ArrayList<>();
            data.add("变为");
            data.add("处于");
            listLabelAdapter.setData(data);
            listLabelAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                    mLinkageCondition.setActionTypeId(position + 1);
                    settingAction.setRightText(mLinkageCondition.getActionTypeId() == 1 ? R.string.linkage_action_become : R.string.linkage_action_keep);
                    mBottomActionDialog.dismiss();
                }
            });
            mBottomActionDialog.setAdapter(listLabelAdapter);
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomActionDialog);
        }
        ListLabelAdapter listLabelAdapter = (ListLabelAdapter) mBottomActionDialog.getAdapter();
        listLabelAdapter.setSelected("");
        mBottomActionDialog.show();
    }
}